package com.icloud.cer.rest.msg;

import java.net.InetSocketAddress;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.icloud.cer.rest.Constants;
import com.icloud.cer.rest.msg.bean.RegistInfo;
import com.icloud.cer.rest.msg.processor.ProcessorManager;
import com.icloud.cer.rest.util.ConnectorManager;
import com.icloud.cer.rest.util.MessageUtils;
import com.icloud.cer.rest.util.SenderManager;

public class EncryptHandler extends IoHandlerAdapter {
	private static final Logger log = LoggerFactory.getLogger(EncryptHandler.class);
	
	private ConnectorManager connectManager;
	
	private ProcessorManager processorManager;
	
	protected SenderManager senderManager;
	
	public ConnectorManager getConnectManager() {
		return connectManager;
	}

	public void setConnectManager(ConnectorManager connectManager) {
		this.connectManager = connectManager;
	}
	
	public ProcessorManager getProcessorManager() {
		return processorManager;
	}

	public void setProcessorManager(ProcessorManager processorManager) {
		this.processorManager = processorManager;
	}

	public SenderManager getSenderManager() {
		return senderManager;
	}

	public void setSenderManager(SenderManager senderManager) {
		this.senderManager = senderManager;
	}

	@Override
	public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
		cause.printStackTrace();
	}

	public void sessionCreated(IoSession session) throws Exception {
		log.info("==============session created================");
	}
	  
	@Override
	public void sessionOpened(IoSession session) throws Exception {
		log.info("==============session open================");
	}
	
	@Override
	public void messageReceived(IoSession session, Object message) throws Exception {
		MessageHolder holder  = (MessageHolder)message;
		short command = holder.getCommand();
		log.info("receive sequence:" + holder.getSequence());
		//不同的消息使用不同的Processor
		processorManager.getProcessor(command).process(session,holder);
		senderManager.notifyBack( holder );	
		//加密机请求注册
//		switch (command) {
//		case MsgConstants.CLIENT_REQ_REG:
//			sendRegMessage(session,holder);
//			break;
//		case MsgConstants.CLIENT_RES_HEARTBEAT:
//			log.info("server recevie heartbeat from client: " + session.getRemoteAddress());
//			break;
//		case MsgConstants.CLIENT_REQ_ENCRYPT:
//			sendEncryptTask(session, holder);
//			break;
//		default:
//			log.error("invalid command:" + command);
//			break;
//		}
		String str = message.toString();
		if (str.trim().equalsIgnoreCase("quit")) {
			session.close();
			return;
		}
	}

	@Override
	public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
		log.info("IDLE " + session.getIdleCount(status) + " session:[" + session.getId() + "]");
	}
	
	@Override
	public void sessionClosed(IoSession session) throws Exception {
		long sessionId = session.getId();
		log.warn("sessionId:" + sessionId + "close." + session);
		connectManager.removeClient(session.getId());
		connectManager.removeSession(session.getId());
	}

	public void messageSent(IoSession session, Object message) throws Exception {
		log.info("sessionId:[" + session.getId() + "] send.");
	}

	

	/**
	 * 如果有任务，则发送，没有则不回复
	 * @param session
	 * @param holder
	 */
	private void sendEncryptTask(IoSession session,MessageHolder holder) {
		long sessionId = session.getId();
		InetSocketAddress clientAddr = connectManager.getClientAddr(sessionId);
		if(clientAddr == null) {
			log.error("客户端没有注册，请重新注册");
			return;
		}
		
		MessageHeader header = MessageUtils.getHeader(Constants.SEQUENCE_LENGTH, MsgConstants.SERVER_SENT_ENCRYPT);
		header.setSize_(8);
		
		RegistInfo reg = new RegistInfo();
		//.setSequence(holder.getSequence());
		
		MessageHolder resHolder = new MessageHolder(MsgConstants.SERVER_SENT_ENCRYPT);
		resHolder.setSequence(holder.getSequence());
		resHolder.setHead(header);
		resHolder.setValue(reg);
		session.write(resHolder);
	}
	
	
}
